<!-- 技术主题趋势 -->
<template>
  <div id="container" class="container">
    <div class="chart" ref="chrtRef" id="trend1"></div>
    <div class="slider">
      <el-slider
        v-model="sliderValue"
        range
        :step="step"
        :marks="marks"
        @change="onChangeSliderValue"
      >
      </el-slider>
    </div>
  </div>
</template>

<script>
import { loadD3v3, loadScript } from "./technologyTopicTrends/require.ts";
import { Drawer, DrawSankey } from "./technologyTopicTrends/drawTrendNew.ts";
import { linkNodeNew, getYears } from "./technologyTopicTrends/trend.ts";
let d3;
let d3Drawer = {};
let chartMap = {};
let sankeyDrawer = {};
let height = 500;
let width = 500;

export default {
  components: {},
  props: {
    chartData: {},
    checkList: [],
    defaultSelect: Number,
  },
  data() {
    return {
      chrtId: "trend1",
      leftValue: 0,
      rightValue: new Date().getFullYear(),
      trendData: {},
      _trendData: {},
      queryType: "trend1",
      marks: {}, // slider
      sliderValue: [0, 100], // slider
      yearArr: [], // slider
      step: 0, // slider
      //列表数据
      tableData: {
        tit: [],
        content: []
      }
    };
  },

  watch: {
    $route() {},
    chartData() {
      // this.handleSilder();
      // this.initMarks(this.yearArr);
      // this.initPage();
    },
    checkList(nv) {
      let arr = []
      nv.forEach((v, i) => {
        let obj = this._trendData.terms.find(b => b.t === v.key)
        if (obj) {
          arr.push(obj)
        }
      })
      this.trendData["terms"] = arr
      this.initPage();
    },
  },
  created() {
    this.ctNavID = this.$route.query.type || "";
  },
  mounted() {
    this.handleSilder();
    this.initMarks(this.yearArr);
    this.initPage();
  },
  methods: {
    handleSilder() {
      this.trendData = this.chartData[0].data;
      this._trendData = JSON.parse(JSON.stringify(this.trendData))
      this.leftValue = this.trendData.start_time || 1960;
      this.rightValue = this.trendData.end_time;
      let { yearArr } = getYears(this.leftValue, this.rightValue);
      this.yearArr = yearArr;
    },
    // 初始化页面
    async initPage() {
      d3 = await new Promise(loadD3v3);
      await new Promise(resolve => {
        loadScript(
          /**
           * `/gdt/lib/sankey-modified.js`   此地址为线上相对路径地址
           * `../../../lib/sankey-modified.js`  本地引用路径
           * */
          `/lib/sankey-modified.js`, //，本地调试时 改为本地引用路径
          { check: ["d3", "sankey"] },
          resolve
        );
      });
      if (!this.trendData || !this.trendData.time_slides) return;
      if (!d3Drawer[this.queryType]) {
        d3Drawer[this.queryType] = new Drawer(d3);
      }
      this.initChart(this.leftValue, this.rightValue);
    },
    initChart(start_time, end_time) {
      const container = this.$refs.chrtRef;
      if (!container || !d3Drawer[this.queryType] || end_time == 0) {
        return null;
      }
      if (chartMap[this.queryType]) {
        chartMap[this.queryType].remove();
      }
      chartMap[this.queryType] = d3Drawer[this.queryType].drawChart(
        `#trend1`,
        {
          width: "100%",
          height: "100%",
          // marginLeft: `330px`,
          zIndex: 1
        },
        this.queryType
      );
      width = container.offsetWidth;
      height = container.offsetHeight;
      let { nodes, links, initYear, q, yearArr } = linkNodeNew(
        this.trendData,
        this.defaultSelect,
        start_time,
        end_time
      );
      const finalTimeSlides = this.renderAxis(start_time, end_time, yearArr);
      this.renderTrendLink(nodes, links, finalTimeSlides);
    },

    renderAxis(startYear, endYear, yearArr) {
      d3Drawer[this.queryType].drawAxis(
        "#vis" + this.queryType,
        yearArr,
        {
          transform: (d, i) =>
            `translate(${i * (width / (yearArr.length - 1))})`
        },
        this.queryType
      );

      d3Drawer[this.queryType].drawLine(
        ".axis" + this.queryType,
        {
          x1: 0,
          y1: 0,
          x2: 0,
          y2: height
        },
        {
          stroke: "lightgray",
          "stroke-width": 1
        }
      );

      d3Drawer[this.queryType].drawText(
        ".axis",
        {
          x: 6,
          y: 10,
          "text-anchor": "start"
        },
        {
          "font-weight": "bold"
        },
        {
          text: "111"
        }
      );

      return yearArr;
    },

    renderTrendLink(nodes, links, finalTimeSlides) {
      sankeyDrawer[this.queryType] = new DrawSankey(d3, [width, height]);
      sankeyDrawer[this.queryType].setData(
        nodes,
        links,
        width / (finalTimeSlides.length > 0 ? finalTimeSlides.length - 1 : 10)
      );
      // 数据导出excle
      this.tableData.content = []
      nodes.map((item, index) => {
        this.tableData.content.push([
          index + 1,
          item.year,
          item.name,
          item.total,
          item.pubs
        ]);
      });
      const sortedStreamChart = d3Drawer[this.queryType].drawG(
        "#vis" + this.queryType,
        {
          id: "trend" + this.queryType,
          height,
          "z-index": 2
        }
      );
      function mouseover() {
        d3.select(this).attr("opacity", 0.6);
        const tar = d3.select(this);
        const groupID = tar.attr("groupID");
        d3.selectAll(".link")
          .filter(d => d.groupID === parseInt(groupID, 10))
          .attr("opacity", 0.6);
        tar.attr("opacity", 0.4);
      }

      function mouseout() {
        d3.selectAll(".link")
          .transition()
          .duration(250)
          .attr("opacity", 0.5);
      }
      const link = sankeyDrawer[this.queryType].drawLink(
        "#trend" + this.queryType,
        {
          mouseout: mouseout,
          mouseover: mouseover
        }
      );

      const node = sankeyDrawer[this.queryType].drawNode(
        "#trend" + this.queryType
      );
      return [link, node];
    },

    // slider
    onChangeSliderValue(val) {
      this.leftValue = Number(this.marks[val[0]]);
      this.rightValue = Number(this.marks[val[1]]);
      this.initPage();
    },

    initMarks(yearArr) {
      let marks = {};
      let len = yearArr.length - 1;
      yearArr.map((it, index) => {
        let i = (100 / len) * index;
        marks[i] = String(it);
      });
      this.marks = marks;
      this.step = 100 / len;
    },
    // 导出报告
    showExport() {
      let subjects = this.$route.query.subjects;
      let str = "";
      if (this.searchTxt !== "") {
        str += this.searchTxt;
        if (subjects) {
          str += " and " + `subjects/${base64.decode(subjects)}`;
        }
      } else if (subjects) {
        str += `subjects/${base64.decode(subjects)}`;
      }
      let ops = {
        sq: str,
        subjects: (subjects && base64.decode(subjects)) || "",
        all_total: this.all_total
      };
      this.$refs.exportReport.init(ops);
    },
    // 导出数据
    exportData() {
      let aoa = [];
      this.tableData.tit = ["index", "date", "name", "total", "pub"];
      aoa = [this.tableData.tit, ...this.tableData.content];
      var ws = XLSX.utils.aoa_to_sheet(
        aoa
      ); /* 新建空workbook，然后加入worksheet */
      var wb = XLSX.utils.book_new(); /*新建book*/
      XLSX.utils.book_append_sheet(
        wb,
        ws,
        name
      ); /* 生成xlsx文件(book,sheet数据,sheet命名) */
      XLSX.writeFile(wb, `技术主题趋势分析数据.xlsx`);
    },
    // 数据处理
    crossFIled() {

    }
  },
  beforeDestroy() {
    this.$Bus.$off("dcData");
  }
};
</script>

<style lang="scss" scoped>
.container {
  // width: 90vw;
  margin: 10px auto;
  border: 1px solid #ccc;
  padding: 18px;
  .chart {
    height: 50vh;
    z-index: 1;
    width: calc(100% - 150px);
    min-height: 50vh;
    color: #fafaff;
    border-radius: 0.5em;
    div {
      width: 100%;
      height: 100%;
    }
  }

  .slider {
    width: calc(100% - 150px);
    height: 62px;
    border-radius: 4px;
  }
}
</style>
<style>
.el-checkbox__input.is-checked + .el-checkbox__label,
.el-checkbox__label {
  color: #2c3e50;
  font-size: 0.16rem;
  margin-bottom: 0.1rem;
  font-family: "微软雅黑", Tahoma, Helvetica, Arial, sans-serif;
}
.c-name {
  color: #2c3e50;
  font-size: 0.16rem;
  font-family: "微软雅黑", Tahoma, Helvetica, Arial, sans-serif;
}
.freq-val {
  color: #2c3e50;
  font-size: 0.18rem;
  font-family: "微软雅黑", Tahoma, Helvetica, Arial, sans-serif;
}
</style>
